//
// Created by changlei on 2022/4/27.
//

import Foundation
import UIKit


class CustomizeTabBar: UITabBar {
    private var highlightedObservations: [UIView: NSKeyValueObservation] = [:]

    override func didAddSubview(_ subview: UIView) {
        super.didAddSubview(subview)
        if let button = subview as? UIControl {
            onAddItem(button)
        }
    }

    override func willRemoveSubview(_ subview: UIView) {
        super.willRemoveSubview(subview)
        if let button = subview as? UIControl {
            onRemoveItem(button)
        }
    }

    deinit {
        highlightedObservations.values.forEach { observation in
            observation.invalidate()
        }
        highlightedObservations.removeAll()
    }

    private func onAddItem(_ button: UIControl) {
        highlightedObservations[button] = button.observe(\.isHighlighted) { (control, change) in
            UIView.animate(withDuration: 0.15) {
                button.alpha = control.isHighlighted ? 0.2 : 1.0
            }
        }
    }

    private func onRemoveItem(_ button: UIControl) {
        highlightedObservations.removeValue(forKey: button)?.invalidate()
    }
}